﻿using System;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using KPIS.GERP.ESS.BLL;
using KPIS.GERP.ESS.MODEL;

using KPIS.DBM;
using KPIS.GERP.GFMS.APP.App_UI.Commons;
using KPIS.GERP.GFMS.BLL;
using KPIS.GERP.GFMS.IBLL;
using KPIS.GERP.GFMS.DAL;
using KPIS.GERP.GFMS.MODEL;
using Telerik.Web.UI;
using System.Globalization;
using System.Web.UI;

namespace KPIS.GERP.GFMS.APP.App_UI.Forms
{
    public partial class FIM_PaymentTax : System.Web.UI.Page
    {
        Main main = new Main();
        IBLL_FIM_Payments pay = new B_FIM_Payments();
        IBLL_FIM_PaymentCheques paycheque = new B_FIM_PaymentCheques();
        IBLL_FIM_MoneyRequests mr = new B_FIM_MoneyRequests();
        IBLL_FIM_MoneyRequestDtls mrd = new B_FIM_MoneyRequestDtls();
        IBLL_FIM_MoneyReturns re = new B_FIM_MoneyReturns();
        IBLL_FIM_MoneyReturnDtls red = new B_FIM_MoneyReturnDtls();
        IBLL_BGM_MAS_Source source = new B_BGM_MAS_Source();
        IBLL_HRM_MP_WorkAreas area = new B_HRM_MP_WorkAreas();
        B_MessageSend send = new B_MessageSend();
        IBLL_FIM_MAS_Events ev = new B_FIM_MAS_Events();
        IBLL_BGM_ProjectOperation oper = new B_BGM_ProjectOperation();
        IBLL_BGM_ProjectOperationReport operRpt = new B_BGM_ProjectOperationReport();
        IBLL_FIM_SystemControls sc = new B_FIM_SystemControls();
        IBLL_HRM_PR_PayrollDtls prd = new B_HRM_PR_PayrollDtls();
        IBLL_FIM_MAS_ExpenseRates rate = new B_FIM_MAS_ExpenseRates();
        IBLL_FIM_MAS_Methods met = new B_FIM_MAS_Methods();
        IBLL_FIM_MAS_BankAccounts acc = new B_FIM_MAS_BankAccounts();
        IBLL_FIM_Cheques cheque = new B_FIM_Cheques();
        IBLL_HRM_PS_Employees emplist = new B_HRM_PS_Employees();
        IBLL_HRM_PS_EMP_BOOK_BANKS emp_acc = new B_HRM_PS_EMP_BOOK_BANKS();
        IBLL_ICM_MasContactBank con_acc = new B_ICM_MasContactBank();
        IBLL_FIM_Payroll prl = new B_FIM_Payroll();
        IBLL_ACM_GENERATE_ACCOUNT_Auto acm = new B_ACM_GENERATE_ACCOUNT_Auto();
        IBLL_FIM_MAS_Contacts con = new B_FIM_MAS_Contacts();
        IBLL_CodeGenerate cg = new B_CodeGenerate();

        public enum Mode
        {
            AddNew,
            Edit,
            ViewAll,
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //======= test only =========
                //Session["EmpSeq"] = "1";
                int year = main.GetSystemControls().default_bgm_year.Value;
                txtBgmYear.Text = year.ToString();
                txtBgmYear.MinValue = year - 10;
                txtBgmYear.MaxValue = year + 1;
                lblBgmYear.Text = year.ToString();

                //===========================

                LoadDDLFilterBgmSourceSeq();
                LoadRblMethodSeq();
                lblBgmSourceName.Text = ddlFilterBgmSourceSeq.SelectedItem.Text;
                LoadDDLBankAccSeq();
                ddlBankAccSeq_SelectedIndexChanged(null, null);
                LoadDDLChequeSeq();
                LoadDDLFromBankAccSeq();
                LoadDDLContact();
                LoadDDLToBankAccSeq(null);
                LoadDDLToContactBankAccSeq(null);
                LoadDDLMonth();
                ddlMonth2.SelectedValue = DateTime.Today.Month.ToString();
                txtYear2.Text = (DateTime.Today.Year + 543).ToString();
                ViewState["_tmpConId"] = null;
                ViewState["_tmpEmpSeq"] = null;
                rblMethodSeq_SelectedIndexChanged(null, null);

                cmdArival_Click(null, null);
            }
        }

        protected void LoadRadGrid1(int? nTaxPaySeq)
        {
            LoadRadGrid1(nTaxPaySeq, null);
        }

        protected void LoadRadGrid1(int? nTaxPaySeq, int? event_seq)
        {
            string strBgmSourceSeq = ddlFilterBgmSourceSeq.SelectedValue;
            string strBgmYear = txtBgmYear.Text;
            string strEventSeq = event_seq.HasValue ? event_seq.ToString() : rblEventSeq.SelectedValue;
            string strContactType = rblContactType.SelectedValue;
            int? nMonth = main.ConvertNullInt(ddlMonth2.SelectedValue);
            int? nYear = main.ConvertNullInt(txtYear2.Text);
            DateTime? dtTax = null;

            if (nMonth != null && nYear != null)
            {
                dtTax = new DateTime(nYear.Value - 543, nMonth.Value, 1).AddMonths(1).AddDays(-1);
            }

            if (strEventSeq == "21")
            {
                RadGrid1.Visible = true;
                PanelPayVat.Visible = false;
                divPayment.Visible = true;
                var list = pay.GetNotPayTax(nTaxPaySeq, strBgmSourceSeq, null/*strBgmYear*/, strContactType);
                if (dtTax != null)
                {
                    list = list.Where(m => m.pay_date <= dtTax).ToList();
                }
                RadGrid1.DataSource = list;
                //RadGrid1.DataBind();
            }
            else if (strEventSeq == "26")
            {
                RadGrid1.Visible = false;
                PanelEdit1.Visible = true;
                PanelPayVat.Visible = true;
                divPayment.Visible = true;  

                var VatModel = pay.GetVatInfo(nTaxPaySeq.ToString());

                if (VatModel != null)
                {
                    lblVatSeq.Text = VatModel.vat_seq.ToString();
                    ddlMonth.SelectedValue = VatModel.month_no.ToString();
                    txtYear.Text = VatModel.year_no.ToString();
                    //CalCulateVat();
                    double dPrevVatAmount = pay.GetPrevVatBuySale(VatModel.month_no, VatModel.year_no);
                    double dVatBuyAmount = VatModel.vat_buy_amount ?? 0;
                    double dVatSaleAmount = VatModel.vat_sale_amount ?? 0;
                    lblPrevVatAmount.Text = dPrevVatAmount.ToString("#,##0.00");
                    lblVatBuyAmount.Text = dVatBuyAmount.ToString("#,##0.00");
                    lblVatSaleAmount.Text = dVatSaleAmount.ToString("#,##0.00");
                    lblVatAmount.Text = (dVatSaleAmount - dVatBuyAmount).ToString("#,##0.00");
                    lblPayAmount.Text = dVatSaleAmount - dVatBuyAmount - dPrevVatAmount > 0 ? (dVatSaleAmount - dVatBuyAmount - dPrevVatAmount).ToString("#,##0.00") : "0.00";
                    lblTotal.Text = (dVatSaleAmount - dVatBuyAmount - dPrevVatAmount).ToString("#,##0.00");

                    lblBuyAmount.Text = (VatModel.buy_amount ?? 0).ToString("#,##0.00");
                    lblSaleAmount.Text = (VatModel.sale_amount ?? 0).ToString("#,##0.00");
                    lblNonVatSaleAmount.Text = (VatModel.non_vat_sale_amount ?? 0).ToString("#,##0.00");
                    lblNext.Text = dVatSaleAmount - dVatBuyAmount > 0 ? "0.00" : (dVatBuyAmount + dPrevVatAmount - dVatSaleAmount).ToString("#,##0.00");

                    //lblCalVatBuyAmount.Text = (VatModel.cal_vat_buy_amount ?? 0).ToString("#,##0.00");
                    lblCalVatSaleAmount.Text = (VatModel.cal_vat_sale_amount ?? 0).ToString("#,##0.00");
                    //lblDiffVatBuyAmount.Text = (VatModel.diff_vat_buy_amount ?? 0).ToString("#,##0.00");
                    lblDiffVatSaleAmount.Text = (VatModel.diff_vat_sale_amount ?? 0).ToString("#,##0.00");

                    divPayment.Visible = (dVatSaleAmount - dVatBuyAmount - dPrevVatAmount) > 0;

                    if (VatModel.pay_seq == null)// || (main.ConvertNullDouble(lblVatAmount.Text) ?? 0) > 0)
                    {
                        UpdateUI1(Mode.Edit, false, true, rblMethodSeq.SelectedValue);
                        return;
                    }

                    nTaxPaySeq = VatModel.pay_seq;
                }
            }

            if (nTaxPaySeq.HasValue)
            {
                var model = pay.GetInfo(nTaxPaySeq.ToString());
                rblEventSeq.Enabled = false;

                lblEventName.Text = model.event_name;
                lblBgmSourceName.Text = model.bgm_source_name;
                lblBgmYear.Text = model.bgm_year.ToString();
                lblPaySeq.Text = nTaxPaySeq.ToString();
                ddlContactSeq.SelectedValue = model.contact_seq.ToString();
                lblRecordStatus.Text = model.record_status;
                bool bApproved = model.record_status == "A";
                bool bEditable = model.record_status == "W" || model.record_status == "R";

                lblPayRefNo.Text = model.ref_no;
                dpPayDate.SetValue(model.pay_date);
                lblRealPayDate.Text = model.real_pay_date.HasValue ? model.real_pay_date.Value.ToShortDateString() : "";
                txtPayName.Text = model.pay_name;
                lblPayAmount.Text = (model.amount ?? 0).ToString("#,##0.00");
                rblMethodSeq.SelectedValue = model.method_seq.ToString();

                UpdateUI1(Mode.Edit, bApproved, bEditable, rblMethodSeq.SelectedValue);
                rblMethodSeq_SelectedIndexChanged(null, null);

                if (PanelTranfer.Visible)
                {
                    DropDownListIDFrom.SelectedValue = model.from_bank_acc_id.ToString();
                    ddlFromBankAcc.SelectedValue = model.from_bank_acc_id.ToString();

                    ddlToBankAcc.SelectedValue = model.to_bank_acc_id.ToString();
                    ddlToConBankAcc.SelectedValue = model.to_bank_acc_id.ToString(); ;
                }

                if (PanelCheque.Visible)
                {
                    LoadDataCheque();
                    //cmdAddNew.Visible = cmdAddNew.Visible = (cmdInsert1.Visible || cmdUpdate1.Visible);
                    PanelEditCheque.Visible = false;
                    cmdInsert2.Visible = true;
                    cmdUpdate2.Visible = false;
                    cmdDelete2.Visible = false;
                    cmdCancel2.Visible = false;
                }
            }
            else
            {
                rblEventSeq.Enabled = true;
                UpdateUI1(Mode.AddNew, false, true, rblMethodSeq.SelectedValue);
            }
        }

        protected void LoadRadGrid2()
        {
            string strBgmSourceSeq = ddlFilterBgmSourceSeq.SelectedValue;
            string strBgmYear = txtBgmYear.Text;
            string strEventSeq = rblEventSeq.SelectedValue;
            string strEmpSeq = Session["EmpSeq"].ToString();
            RadGrid2.DataSource = pay.GetFull(strBgmSourceSeq, strBgmYear, null, strEventSeq, "0");
        }

        protected void UpdateUI1(Mode mode, bool bApproved, bool bEditable, string strMethodSeq)
        {
            switch (mode)
            {
                case Mode.AddNew:
                    cmdInsert1.Visible = true;
                    cmdUpdate1.Visible = false;
                    cmdCancel1.Visible = false;
                    cmdDelete1.Visible = false;
                    cmdApprove.Visible = false;
                    cmdRealPay.Visible = false;
                    cmdAddNew.Visible = true;

                    PanelEdit1.Visible = true;
                    PanelView.Visible = false;
                    PanelMessageSend.Visible = false;
                    PanelEditCheque.Visible = false;
                    PanelRealPay.Visible = false;

                    ClearUI();
                    break;
                case Mode.Edit:
                    cmdInsert1.Visible = false;
                    cmdUpdate1.Visible = true;
                    cmdCancel1.Visible = true;
                    cmdDelete1.Visible = true;
                    cmdApprove.Visible = true;
                    cmdRealPay.Visible = strMethodSeq == "1" && bApproved && lblRealPayDate.Text.Length == 0;
                    cmdAddNew.Visible = bEditable;

                    cmdUpdate1.Enabled = bEditable;
                    cmdDelete1.Enabled = bEditable;
                    cmdApprove.Enabled = bEditable;

                    PanelEdit1.Visible = true;
                    PanelView.Visible = false;
                    PanelMessageSend.Visible = false;
                    PanelEditCheque.Visible = false;
                    PanelRealPay.Visible = false;
                    break;
                case Mode.ViewAll:
                    PanelEdit1.Visible = false;
                    PanelView.Visible = true;
                    break;
            }
        }

        private void ClearUI()
        {
            lblPaySeq.Text = "";
            lblRecordStatus.Text = "W";
            lblPayRefNo.Text = "";
            dpPayDate.SetValue(DateTime.Today);
            lblRealPayDate.Text = "";
            txtPayName.Text = "";
            lblPayAmount.Text = "0.00";
            ViewState["Cheque"] = new List<M_FIM_PaymentCheques>();
            LoadDataCheque();

            ddlMonth.SelectedValue = DateTime.Today.Month.ToString();
            //ddlMonth2.SelectedValue = DateTime.Today.Month.ToString();
            txtYear.Text = (DateTime.Today.Year + 543).ToString();
            //txtYear2.Text = (DateTime.Today.Year + 543).ToString();
        }
        private void LoadDDLMonth()
        {
            CultureInfo _thCulture = new CultureInfo("th-TH");

            for (int i = 1; i <= 12; i++)
            {
                DateTime Tempdate = new DateTime(DateTime.Now.Year, i, 1);
                RadComboBoxItem item = new RadComboBoxItem();
                item.Text = Tempdate.ToString("MMMM", _thCulture);
                item.Value = Convert.ToInt32(i).ToString();
                ddlMonth.Items.Add(item);
                RadComboBoxItem item2 = new RadComboBoxItem();
                item2.Text = Tempdate.ToString("MMMM", _thCulture);
                item2.Value = Convert.ToInt32(i).ToString();
                ddlMonth2.Items.Add(item2);
            }
        }

        //protected void LoadData(string strPaySeq)
        //{
        //    M_FIM_Payments payInfo = pay.GetInfo(strPaySeq);
        //    lblBgmSourceName.Text = payInfo.event_name;
        //    lblBgmYear.Text = payInfo.bgm_year.ToString();
        //    lblEventSeq.Text = payInfo.event_seq.ToString();
        //    lblEmpSeq.Text = payInfo.emp_seq.ToString();
        //    lblContactSeq.Text = payInfo.contact_seq.ToString();

        //    lblPayAmount.Text = (payInfo.amount ?? 0).ToString("#,##0.00");

        //    if (!String.IsNullOrEmpty(lblContactSeq.Text))
        //    {
        //        ViewState["_tmpConId"] = lblContactSeq.Text;
        //        ViewState["_tmpEmpSeq"] = null;
        //    }
        //    else {
        //        ViewState["_tmpEmpSeq"] = lblEmpSeq.Text;
        //        ViewState["_tmpConId"] = null;
        //    }

        //    lblPaySeq.Text = strPaySeq;
        //    lblPayRefNo.Text = payInfo.ref_no;
        //    dpPayDate.SetValue(payInfo.pay_date.Value);
        //    txtPayName.Text = payInfo.pay_name;
        //    rblMethodSeq.SelectedValue = payInfo.method_seq.ToString();

        //    if (rblMethodSeq.SelectedValue.Equals("2"))
        //    {
        //        ddlFromBankAcc.SelectedValue = payInfo.from_bank_acc_id.ToString();
        //        ddlToBankAcc.SelectedValue = payInfo.to_bank_acc_id.ToString();
        //    }
        //    else if (rblMethodSeq.SelectedValue.Equals("3"))
        //    {
        //        ddlToBankAcc.SelectedValue = payInfo.to_bank_acc_id.ToString();
        //    }

        //    if (PanelCheque.Visible)
        //    {
        //        LoadDataCheque();
        //        cmdAddNew.Visible = cmdAddNew.Visible = (cmdInsert1.Visible || cmdUpdate1.Visible);
        //        PanelEditCheque.Visible = false;
        //        cmdInsert2.Visible = true;
        //        cmdUpdate2.Visible = false;
        //        cmdDelete2.Visible = false;
        //        cmdCancel2.Visible = false;
        //        PanelTranfer.Visible = false;
        //    }
        //}

        protected void LoadDDLContact()
        {
            ddlContactSeq.DataSource = con.GetList(null);
            ddlContactSeq.DataBind();

            ddlContactSeq.SelectedValue = "";
        }

        protected void LoadDataCheque()
        {
            if (lblPaySeq.Text.Length == 0)
            {
                ViewState["Cheque"] = paycheque.GetFull("-1", null);
            }
            else
            {
                ViewState["Cheque"] = paycheque.GetFull(lblPaySeq.Text, null);
            }

            grdCheque.DataSource = (IList<M_FIM_PaymentCheques>)ViewState["Cheque"];
            grdCheque.DataBind();
        }

        protected void LoadDDLFilterBgmSourceSeq()
        {
            ddlFilterBgmSourceSeq.DataSource = source.GetFull(true);
            ddlFilterBgmSourceSeq.DataBind();

            ddlFilterBgmSourceSeq.SelectedIndex = 0;
        }

        protected void LoadRblMethodSeq()
        {
            rblMethodSeq.DataSource = met.GetList();
            rblMethodSeq.DataBind();

            if (rblMethodSeq.Items.Count > 0)
            {
                rblMethodSeq.SelectedIndex = 0;
            }
        }

        protected void LoadDDLBankAccSeq()
        {
            ddlBankAccSeq.DataSource = acc.GetList("2", ddlFilterBgmSourceSeq.SelectedValue, null, null);
            ddlBankAccSeq.DataBind();

            ddlBankAccSeq.SelectedIndex = 0;
            LoadDDLChequeSeq();
        }

        protected void LoadDDLFromBankAccSeq()
        {
            ddlFromBankAcc.DataSource = acc.GetList(null, ddlFilterBgmSourceSeq.SelectedValue, null, null);
            ddlFromBankAcc.DataBind();
            ddlFromBankAcc.SelectedIndex = 0;
        }

        protected void LoadDDLToBankAccSeq(int? emp_seq)
        {
            ddlToBankAcc.DataSource = emp_acc.GetList(emp_seq);
            ddlToBankAcc.DataBind();
            ddlToBankAcc.SelectedIndex = 0;
        }

        protected void LoadDDLToContactBankAccSeq(int? ConId)
        {
            ddlToConBankAcc.DataSource = con_acc.GetList(ConId);
            ddlToConBankAcc.DataBind();
            ddlToConBankAcc.SelectedIndex = 0;
        }

        protected void LoadDDLChequeSeq()
        {
            if (lblPaySeq.Text.Length == 0)
            {
                ddlChequeSeq.DataSource = cheque.GetList(ddlBankAccSeq.SelectedValue, null, null, "1");
            }
            else
            {
                ddlChequeSeq.DataSource = cheque.GetList(ddlBankAccSeq.SelectedValue, lblPaySeq.Text, null, "1");
            }
            ddlChequeSeq.DataBind();

            main.InsertEmptyDDLSelect(ddlChequeSeq);
            ddlChequeSeq.SelectedIndex = 0;
        }

        protected bool CheckData1()
        {
            bool bOK = true;
            string strError = "";

            if (dpPayDate.GetStringValue().Length == 0)
            {
                bOK = false;
                strError = main.ErrorEmpty("วันที่ทำรายการ");
            }
            else if (txtPayName.Text.Length == 0)
            {
                bOK = false;
                strError = main.ErrorEmpty("ชื่อรายการจ่ายเงิน");
            }
            else if (ddlContactSeq.SelectedValue.Length == 0)
            {
                bOK = false;
                strError = main.ErrorEmpty("สั่งจ่าย");
            }
            else if (rblEventSeq.SelectedValue == "21" && RadGrid1.SelectedItems.Count == 0)
            {
                bOK = false;
                strError = "กรุณาเลือกรายการที่นำส่งภาษี";
            }
            else if (rblEventSeq.SelectedValue == "26" && (main.ConvertNullDouble(txtYear.Text) ?? 0) == 0)
            {
                bOK = false;
                strError = main.ErrorEmpty("ปีที่คิดคำนวณ");
            }

            if (rblMethodSeq.SelectedIndex.Equals(2))
            {
                if (String.IsNullOrEmpty(ddlFromBankAcc.SelectedValue))
                {
                    bOK = false;
                    strError = main.ErrorEmpty("บัญชีโอน");
                }
            }

            if (rblMethodSeq.SelectedIndex.Equals(2) || rblMethodSeq.SelectedIndex.Equals(3))
            {
                if (ViewState["_tmpConId"] != null)
                {
                    if (String.IsNullOrEmpty(ddlToConBankAcc.SelectedValue))
                    {
                        bOK = false;
                        strError = main.ErrorEmpty("บัญชีรับ");
                    }
                }
                else
                {
                    if (String.IsNullOrEmpty(ddlToBankAcc.SelectedValue))
                    {
                        bOK = false;
                        strError = main.ErrorEmpty("บัญชีรับ");
                    }
                }
            }

            if (!bOK)
                main.MessageAlert(Page, strError);

            return bOK;
        }

        protected bool CheckData2()
        {
            bool bOK = true;
            string strError = "";

            if (ddlBankAccSeq.SelectedValue.Length == 0)
            {
                bOK = false;
                strError = main.ErrorEmpty("บัญชีเงินฝาก");
            }
            else if (ddlChequeSeq.SelectedValue.Length == 0)
            {
                bOK = false;
                strError = main.ErrorEmpty("เช็คเลขที่");
            }
            else if (txtChequeAmount.Text.Length == 0)
            {
                bOK = false;
                strError = main.ErrorEmpty("จำนวนเงิน");
            }

            if (!bOK)
                main.MessageAlert(Page, strError);

            return bOK;
        }

        //============================ control events ==============================

        protected void RadGrid1_SelectedIndexChanged(object sender, EventArgs e)
        {
            decimal dTaxAmount = 0;

            if (RadGrid1.SelectedItems.Count > 0)
            {
                foreach (GridDataItem item in RadGrid1.SelectedItems)
                {
                    dTaxAmount += (main.ConvertNullDecimal(main.WebString(item["tax"].Text)) ?? 0);
                }
            }

            lblPayAmount.Text = dTaxAmount.ToString("#,##0.00");
        }

        protected void RadGrid1_NeedDataSource(object source, GridNeedDataSourceEventArgs e)
        {
            if (!e.IsFromDetailTable)
            {
                LoadRadGrid1(null);
            }
        }

        protected void RadGrid2_ItemCommand(object source, GridCommandEventArgs e)
        {
            if (e.CommandName == "RowClick")
            {
                GridDataItem item = (GridDataItem)e.Item;
                string strPaySeq = main.WebString(item["pay_seq"].Text);

                LoadRadGrid1(Convert.ToInt32(strPaySeq), Convert.ToInt32(main.WebString(item["event_seq"].Text)));
                RadGrid1.DataBind();

                if (rblEventSeq.SelectedValue == "21")
                {
                    RadGrid1_SelectedIndexChanged(null, null);
                }
            }
        }

        protected void RadGrid2_NeedDataSource(object source, GridNeedDataSourceEventArgs e)
        {
            if (!e.IsFromDetailTable)
            {
                LoadRadGrid2();
            }
        }

        protected void grdCheque_ItemCommand(object source, GridCommandEventArgs e)
        {
            if (e.CommandName == "cmdEdit")
            {
                GridDataItem item = (GridDataItem)e.Item;

                PanelEditCheque.Visible = true;
                cmdAddNew.Visible = false;
                cmdInsert2.Visible = false;
                cmdUpdate2.Visible = cmdUpdate1.Visible;
                cmdDelete2.Visible = cmdUpdate1.Visible;
                cmdCancel2.Visible = true;

                lblPayChequeSeq.Text = main.WebString(item["pay_cheque_seq"].Text);
                ddlBankAccSeq.SelectedValue = main.WebString(item["bank_acc_seq"].Text);
                LoadDDLChequeSeq();
                ddlChequeSeq.SelectedValue = main.WebString(item["cheque_seq"].Text);
                txtChequeAmount.Text = main.WebString(item["amount"].Text);
                lblIndex.Text = item.ItemIndex.ToString();
            }
            else if (e.CommandName == "cmdPayCheque")
            {
                PanelPayCheque.Visible = true;

                GridDataItem item = (GridDataItem)e.Item;
                M_FIM_Cheques model = cheque.GetInfo(main.WebString(item["cheque_seq"].Text));

                lblChequeSeq.Text = model.cheque_seq.ToString();
                lblChequeBookSeq.Text = model.cheque_book_seq.ToString();
                lblChequeNo.Text = model.cheque_no.ToString();
                lblBankAccSeq.Text = model.bank_acc_seq.ToString();
                dpChequePayDate.SetValue(model.pay_date);
                dpChequeDate.SetValue(model.cheque_date);
                txtReceiver.Text = model.receiver;
                rblChequeStatus.SelectedValue = model.cheque_status;
                rblChequeStatus_SelectedIndexChanged(null, null);
                txtActualPayDate.SetValue(model.pay_date);
                // txtChequeRemarks.Text = model.cheque_remarks;
            }
        }

        protected void grdCheque_ItemDataBound(object sender, GridItemEventArgs e)
        {
            if (e.Item.ItemType == GridItemType.Item || e.Item.ItemType == GridItemType.AlternatingItem)
            {
                GridDataItem dataItem = (GridDataItem)e.Item;
                string ChequeStatus = main.WebString(dataItem["cheque_status"].Text);

                ((LinkButton)e.Item.FindControl("cmdEdit")).Visible = lblRecordStatus.Text == "W" || lblRecordStatus.Text == "R";
                ((Button)e.Item.FindControl("cmdPayCheque")).Visible = (ChequeStatus == "1" || ChequeStatus == "2");// && lblRecordStatus.Text == "A";
            }
        }

        protected void cmdAddNew_Click(object sender, EventArgs e)
        {
            PanelEditCheque.Visible = true;

            cmdAddNew.Visible = false;
            cmdDelete2.Visible = false;
            cmdInsert2.Visible = (cmdUpdate1.Visible || cmdInsert1.Visible);
            cmdUpdate2.Visible = false;
            divControl1.Visible = false;

            ddlChequeSeq.SelectedIndex = 0;
            txtChequeAmount.Text = lblPayAmount.Text;
        }

        protected void cmdDelete1_Click(object sender, EventArgs e)
        {
            if (rblEventSeq.SelectedValue == "26")
            {
                string strVatSeq = lblVatSeq.Text;

                pay.DeleteVatDtls(strVatSeq);
                pay.DeleteVat(strVatSeq, new SsMng().EmpSeqI);
            }

            string strPaySeq = lblPaySeq.Text;

            if (strPaySeq.Length > 0)
            {
                M_FIM_Payments info = new M_FIM_Payments();
                info.pay_seq = Convert.ToInt32(strPaySeq);
                info.updated_by = main.ConvertNullInt(Session["EmpSeq"].ToString());
                info.updated_when = DateTime.Now;

                pay.Delete(info);
            }

            PanelEdit1.Visible = false;
            PanelView.Visible = true;
            LoadRadGrid2();
            RadGrid2.DataBind();
        }

        protected void cmdInsert1_Click(object sender, EventArgs e)
        {
            string strPaySeq = "";
            string strEventSeq = rblEventSeq.SelectedValue;
            string strAmount = lblPayAmount.Text;
            double dAmount = main.ConvertNullDouble(strAmount) ?? 0;

            if (strEventSeq == "26" && dAmount == 0)
            {
                InsertVat(null);
                main.MessageAlert(Page, "บันทึกเรียบร้อย");
                cmdHistory_Click(null, null);
                return;
            }
            else
            {
                if (!CheckData1())
                {
                    return;
                }

                M_FIM_Payments info = new M_FIM_Payments();

                string strBgmSourceSeq = ddlFilterBgmSourceSeq.SelectedValue;
                string strBgmYear = txtBgmYear.Text;

                string strPayName = txtPayName.Text;
                string strRefNo = cg.GetNextCode(TransectionType.FimPaymentsRefNo, strBgmSourceSeq == "1" ? "1" : "2");
                DateTime strPayDate = dpPayDate.GetDateValue().Value;
                string strEmpSeq = null;
                string strContactSeq = ddlContactSeq.SelectedValue;
                string strMethodSeq = rblMethodSeq.SelectedValue;
                string strUserID = Session["EmpSeq"].ToString();
                string strFromBankAcc = ddlFromBankAcc.SelectedValue;
                string strToBankAcc = ddlToBankAcc.SelectedValue;
                string strToConBankAcc = ddlToConBankAcc.SelectedValue;

                DateTime dtNow = DateTime.Now;

                info.bgm_source_seq = Convert.ToInt32(strBgmSourceSeq);
                info.bgm_year = Convert.ToInt32(strBgmYear);
                info.event_seq = main.ConvertNullInt(strEventSeq);
                info.pay_name = strPayName;
                info.ref_no = strRefNo;
                info.pay_date = main.ConvertNullDateTime(strPayDate);
                info.emp_seq = main.ConvertNullInt(strEmpSeq);
                info.contact_seq = main.ConvertNullInt(strContactSeq);
                info.method_seq = main.ConvertNullInt(strMethodSeq);
                info.amount = main.ConvertNullDouble(strAmount);

                info.created_by = main.ConvertNullInt(strUserID);
                info.created_when = main.ConvertNullDateTime(dtNow);

                if (PanelTranfer.Visible)
                {
                    if (ViewState["_tmpConId"] != null)
                        info.to_bank_acc_id = main.ConvertNullInt(strToConBankAcc);
                    else
                        info.to_bank_acc_id = main.ConvertNullInt(strToBankAcc);


                    if (rblMethodSeq.SelectedIndex.Equals(2))
                        info.from_bank_acc_id = main.ConvertNullInt(strFromBankAcc);
                    else if (rblMethodSeq.SelectedIndex.Equals(3))
                        info.from_bank_acc_id = null;
                }

                strPaySeq = pay.Insert(info);

                if (PanelCheque.Visible)
                {
                    foreach (GridDataItem item in grdCheque.Items)
                    {
                        M_FIM_PaymentCheques chequeInfo = new M_FIM_PaymentCheques();
                        chequeInfo.pay_seq = main.ConvertNullInt(strPaySeq);
                        chequeInfo.cheque_seq = main.ConvertNullInt(main.WebString(item["cheque_seq"].Text));
                        chequeInfo.amount = main.ConvertNullDouble(main.WebString(item["amount"].Text));
                        chequeInfo.record_status = "W";
                        chequeInfo.created_by = main.ConvertNullInt(Session["EmpSeq"]);
                        chequeInfo.created_when = DateTime.Now;

                        paycheque.Insert(chequeInfo);
                    }
                }

                if (strEventSeq == "21")
                {
                    foreach (GridDataItem item in RadGrid1.SelectedItems)
                    {
                        int nPaySeq = Convert.ToInt32(main.WebString(item["pay_seq"].Text));
                        pay.UpdateTaxPaySeq(nPaySeq, Convert.ToInt32(strPaySeq), Convert.ToInt32(Session["EmpSeq"]));
                    }
                }
                else if (strEventSeq == "26")
                {
                    InsertVat(strPaySeq);
                }

                main.MessageAlert(Page, "รหัสรายการคือ [" + strRefNo + "]");

                LoadRadGrid1(Convert.ToInt32(strPaySeq));
                RadGrid1.DataBind();

                RadGrid1_SelectedIndexChanged(null, null);
            }
        }

        private void InsertVat(string strPaySeq)
        {
            int nMonth = main.ConvertNullInt(ddlMonth.SelectedValue) ?? 1;
            int nBgmYear = main.ConvertNullInt(txtBgmYear.Text) ?? 0;
            int nYear = main.ConvertNullInt(txtYear.Text) ?? 0;
            int nBgmSourceSeq = main.ConvertNullInt(ddlFilterBgmSourceSeq.SelectedValue) ?? 1;
            double dSaleAmount = main.ConvertNullDouble(lblSaleAmount.Text) ?? 0;
            double dVatSaleAmount = main.ConvertNullDouble(lblVatSaleAmount.Text) ?? 0;
            double dNonVatSaleAmount = main.ConvertNullDouble(lblNonVatSaleAmount.Text) ?? 0;
            double dBuyAmount = main.ConvertNullDouble(lblBuyAmount.Text) ?? 0;
            double dVatBuyAmount = main.ConvertNullDouble(lblVatBuyAmount.Text) ?? 0;
            //double dCalVatBuyAmount = main.ConvertNullDouble(lblCalVatBuyAmount.Text) ?? 0;
            double dCalVatSaleAmount = main.ConvertNullDouble(lblCalVatSaleAmount.Text) ?? 0;
            //double dDiffVatBuyAmount = main.ConvertNullDouble(lblDiffVatBuyAmount.Text) ?? 0;
            double dDiffVatSaleAmount = main.ConvertNullDouble(lblDiffVatSaleAmount.Text) ?? 0;

            double dNextMonthVatAmount = main.ConvertNullDouble(lblNext.Text) ?? 0;

            var model = new M_FIM_Vat()
            {
                bgm_source_seq = nBgmSourceSeq,
                bgm_year = nBgmYear,
                year_no = nYear,
                month_no = nMonth,
                sale_amount = dSaleAmount,
                vat_sale_amount = dVatSaleAmount,
                non_vat_sale_amount = dNonVatSaleAmount,
                buy_amount = dBuyAmount,
                vat_buy_amount = dVatBuyAmount,
                pay_seq = main.ConvertNullInt(strPaySeq),
                next_month_vat_amount = dNextMonthVatAmount,
                //cal_vat_buy_amount = dCalVatBuyAmount,
                cal_vat_sale_amount = dCalVatSaleAmount,
                //diff_vat_buy_amount = dDiffVatBuyAmount,
                diff_vat_sale_amount = dDiffVatSaleAmount,
                record_status = "W",
                created_by = new SsMng().EmpSeqI,
                created_when = DateTime.Now,
            };

            string VatSeq = pay.InsertVat(model);
            int nVatSeq = Convert.ToInt32(VatSeq);

            var PayModels = pay.GetIncludeVatPayment(nMonth, nYear, null, null);

            foreach (var PayModel in PayModels)
            {
                var modelDtls = new M_FIM_Vat_Dtls()
                {
                    vat_seq = nVatSeq,
                    pay_seq = PayModel.pay_seq,
                    vat_buy_amount = PayModel.vat,
                };
                pay.InsertVatDtls(modelDtls);
            }

            var ReturnModels = pay.GetIncludeVatReturnDtls(nMonth, nYear, null, null);

            foreach (var ReturnModel in ReturnModels)
            {
                var modelDtls = new M_FIM_Vat_Dtls()
                {
                    vat_seq = nVatSeq,
                    return_dtls_seq = ReturnModel.return_dtls_seq,
                    vat_buy_amount = ReturnModel.vat_amount,
                };
                pay.InsertVatDtls(modelDtls);
            }

            var RecModels = pay.GetIncludeVatReceive(nMonth, nYear, null, null);

            foreach (var RecModel in RecModels)
            {
                var modelDtls = new M_FIM_Vat_Dtls()
                {
                    vat_seq = nVatSeq,
                    receive_seq = RecModel.receive_seq,
                    vat_sale_amount = main.ConvertNullDouble(RecModel.vat_amount),
                };
                pay.InsertVatDtls(modelDtls);
            }
        }

        private void UpdateVat(string strPaySeq)
        {
            int nVatSeq = Convert.ToInt32(lblVatSeq.Text);
            int nMonth = main.ConvertNullInt(ddlMonth.SelectedValue) ?? 1;
            int nBgmYear = main.ConvertNullInt(txtBgmYear.Text) ?? 0;
            int nYear = main.ConvertNullInt(txtYear.Text) ?? 0;
            int nBgmSourceSeq = main.ConvertNullInt(ddlFilterBgmSourceSeq.SelectedValue) ?? 1;
            double dSaleAmount = main.ConvertNullDouble(lblSaleAmount.Text) ?? 0;
            double dVatSaleAmount = main.ConvertNullDouble(lblVatSaleAmount.Text) ?? 0;
            double dNonVatSaleAmount = main.ConvertNullDouble(lblNonVatSaleAmount.Text) ?? 0;
            double dBuyAmount = main.ConvertNullDouble(lblBuyAmount.Text) ?? 0;
            double dVatBuyAmount = main.ConvertNullDouble(lblVatBuyAmount.Text) ?? 0;
            //double dCalVatBuyAmount = main.ConvertNullDouble(lblCalVatBuyAmount.Text) ?? 0;
            double dCalVatSaleAmount = main.ConvertNullDouble(lblCalVatSaleAmount.Text) ?? 0;
            //double dDiffVatBuyAmount = main.ConvertNullDouble(lblDiffVatBuyAmount.Text) ?? 0;
            double dDiffVatSaleAmount = main.ConvertNullDouble(lblDiffVatSaleAmount.Text) ?? 0;

            double dNextMonthVatAmount = main.ConvertNullDouble(lblNext.Text) ?? 0;

            var model = pay.GetVatInfo(lblVatSeq.Text);
            model.sale_amount = dSaleAmount;
            model.vat_sale_amount = dVatSaleAmount;
            model.non_vat_sale_amount = dNonVatSaleAmount;
            model.buy_amount = dBuyAmount;
            model.vat_buy_amount = dVatBuyAmount;
            //model.cal_vat_buy_amount = dCalVatBuyAmount;
            model.cal_vat_sale_amount = dCalVatSaleAmount;
            //model.diff_vat_buy_amount = dDiffVatBuyAmount;
            model.diff_vat_sale_amount = dDiffVatSaleAmount;
            model.pay_seq = main.ConvertNullInt(strPaySeq);
            model.next_month_vat_amount = dNextMonthVatAmount;
            model.updated_by = new SsMng().EmpSeqI;
            model.updated_when = DateTime.Now;

            pay.UpdateVat(model);
            pay.DeleteVatDtls(nVatSeq.ToString());

            var PayModels = pay.GetIncludeVatPayment(nMonth, nYear, null, null);

            foreach (var PayModel in PayModels)
            {
                var modelDtls = new M_FIM_Vat_Dtls()
                {
                    vat_seq = nVatSeq,
                    pay_seq = PayModel.pay_seq,
                    vat_buy_amount = PayModel.vat,
                };
                pay.InsertVatDtls(modelDtls);
            }

            var ReturnModels = pay.GetIncludeVatReturnDtls(nMonth, nYear, null, null);

            foreach (var ReturnModel in ReturnModels)
            {
                var modelDtls = new M_FIM_Vat_Dtls()
                {
                    vat_seq = nVatSeq,
                    return_dtls_seq = ReturnModel.return_dtls_seq,
                    vat_buy_amount = ReturnModel.vat_amount,
                };
                pay.InsertVatDtls(modelDtls);
            }

            var RecModels = pay.GetIncludeVatReceive(nMonth, nYear, null, null);

            foreach (var RecModel in RecModels)
            {
                var modelDtls = new M_FIM_Vat_Dtls()
                {
                    vat_seq = nVatSeq,
                    receive_seq = RecModel.receive_seq,
                    vat_sale_amount = main.ConvertNullDouble(RecModel.vat_amount),
                };
                pay.InsertVatDtls(modelDtls);
            }
        }

        protected void cmdUpdate1_Click(object sender, EventArgs e)
        {
            string strPaySeq = lblPaySeq.Text;
            string strEventSeq = rblEventSeq.SelectedValue;
            string strAmount = lblPayAmount.Text;
            double dAmount = main.ConvertNullDouble(strAmount) ?? 0;

            if (strEventSeq == "26" && dAmount == 0)
            {
                UpdateVat(null);

                if (strPaySeq.Length > 0)
                {
                    pay.Delete(new M_FIM_Payments() { pay_seq = Convert.ToInt32(strPaySeq), updated_by = new SsMng().EmpSeqI, updated_when = DateTime.Now });

                    var chequeModels = paycheque.GetPaymentCheques(strPaySeq);

                    foreach (var chequeModel in chequeModels)
                    {
                        chequeModel.updated_by = new SsMng().EmpSeqI;
                        chequeModel.updated_when = DateTime.Now;
                        paycheque.Delete(chequeModel);
                    }
                }

                main.MessageAlert(Page, "บันทึกเรียบร้อย");
                cmdHistory_Click(null, null);
            }
            else
            {
                if (!CheckData1())
                {
                    return;
                }

                if (strPaySeq.Length > 0)
                {
                    M_FIM_Payments info = new M_FIM_Payments();

                    string strBgmSourceSeq = ddlFilterBgmSourceSeq.SelectedValue;
                    string strBgmYear = txtBgmYear.Text;
                    string strPayName = txtPayName.Text;
                    string strRefNo = lblPayRefNo.Text;
                    DateTime strPayDate = dpPayDate.GetDateValue().Value;
                    //string strEmpSeq = (lblEmpSeq.Text.Length > 0 ? lblEmpSeq.Text : null);
                    string strContactSeq = ddlContactSeq.SelectedValue;
                    string strMethodSeq = rblMethodSeq.SelectedValue;
                    string strFromBankAcc = ddlFromBankAcc.SelectedValue;
                    string strToBankAcc = ddlToBankAcc.SelectedValue;
                    string strToConBankAcc = ddlToConBankAcc.SelectedValue;

                    string strUserID = Session["EmpSeq"].ToString();

                    DateTime dtNow = DateTime.Now;

                    info.pay_seq = Convert.ToInt32(strPaySeq);
                    info.bgm_source_seq = Convert.ToInt32(strBgmSourceSeq);
                    info.bgm_year = Convert.ToInt32(strBgmYear);
                    info.event_seq = main.ConvertNullInt(strEventSeq);
                    info.pay_name = strPayName;
                    info.ref_no = strRefNo;
                    info.pay_date = main.ConvertNullDateTime(strPayDate);
                    info.emp_seq = null;
                    info.contact_seq = main.ConvertNullInt(strContactSeq);
                    info.method_seq = main.ConvertNullInt(strMethodSeq);
                    info.amount = main.ConvertNullDouble(strAmount);

                    info.updated_by = main.ConvertNullInt(strUserID);
                    info.updated_when = main.ConvertNullDateTime(dtNow);

                    if (PanelTranfer.Visible)
                    {
                        if (ViewState["_tmpConId"] != null)
                            info.to_bank_acc_id = main.ConvertNullInt(strToConBankAcc);
                        else
                            info.to_bank_acc_id = main.ConvertNullInt(strToBankAcc);

                        if (rblMethodSeq.SelectedIndex.Equals(2))
                            info.from_bank_acc_id = main.ConvertNullInt(strFromBankAcc);
                        else if (rblMethodSeq.SelectedIndex.Equals(3))
                            info.from_bank_acc_id = null;
                    }

                    pay.Update(info);
                }
                else
                {
                    M_FIM_Payments info = new M_FIM_Payments();

                    string strBgmSourceSeq = ddlFilterBgmSourceSeq.SelectedValue;
                    string strBgmYear = txtBgmYear.Text;
                    string strPayName = txtPayName.Text;
                    string strRefNo = cg.GetNextCode(TransectionType.FimPaymentsRefNo, strBgmSourceSeq == "1" ? "1" : "2");
                    DateTime strPayDate = dpPayDate.GetDateValue().Value;
                    string strEmpSeq = null;
                    string strContactSeq = ddlContactSeq.SelectedValue;
                    string strMethodSeq = rblMethodSeq.SelectedValue;
                    string strUserID = Session["EmpSeq"].ToString();
                    string strFromBankAcc = ddlFromBankAcc.SelectedValue;
                    string strToBankAcc = ddlToBankAcc.SelectedValue;
                    string strToConBankAcc = ddlToConBankAcc.SelectedValue;

                    DateTime dtNow = DateTime.Now;

                    info.bgm_source_seq = Convert.ToInt32(strBgmSourceSeq);
                    info.bgm_year = Convert.ToInt32(strBgmYear);
                    info.event_seq = main.ConvertNullInt(strEventSeq);
                    info.pay_name = strPayName;
                    info.ref_no = strRefNo;
                    info.pay_date = main.ConvertNullDateTime(strPayDate);
                    info.emp_seq = main.ConvertNullInt(strEmpSeq);
                    info.contact_seq = main.ConvertNullInt(strContactSeq);
                    info.method_seq = main.ConvertNullInt(strMethodSeq);
                    info.amount = main.ConvertNullDouble(strAmount);

                    info.created_by = main.ConvertNullInt(strUserID);
                    info.created_when = main.ConvertNullDateTime(dtNow);

                    if (PanelTranfer.Visible)
                    {
                        if (ViewState["_tmpConId"] != null)
                            info.to_bank_acc_id = main.ConvertNullInt(strToConBankAcc);
                        else
                            info.to_bank_acc_id = main.ConvertNullInt(strToBankAcc);


                        if (rblMethodSeq.SelectedIndex.Equals(2))
                            info.from_bank_acc_id = main.ConvertNullInt(strFromBankAcc);
                        else if (rblMethodSeq.SelectedIndex.Equals(3))
                            info.from_bank_acc_id = null;
                    }

                    strPaySeq = pay.Insert(info);
                }

                if (PanelCheque.Visible)
                {
                    foreach (GridDataItem item in grdCheque.Items)
                    {
                        M_FIM_PaymentCheques chequeInfo = new M_FIM_PaymentCheques();
                        chequeInfo.pay_seq = main.ConvertNullInt(strPaySeq);
                        chequeInfo.cheque_seq = main.ConvertNullInt(main.WebString(item["cheque_seq"].Text));
                        chequeInfo.amount = main.ConvertNullDouble(main.WebString(item["amount"].Text));
                        chequeInfo.record_status = "W";

                        if (main.WebString(item["pay_cheque_seq"].Text).Length == 0)
                        {
                            chequeInfo.created_by = main.ConvertNullInt(Session["EmpSeq"]);
                            chequeInfo.created_when = DateTime.Now;
                            paycheque.Insert(chequeInfo);
                        }
                        else
                        {
                            chequeInfo.pay_cheque_seq = Convert.ToInt32(main.WebString(item["pay_cheque_seq"].Text));
                            chequeInfo.updated_by = main.ConvertNullInt(Session["EmpSeq"]);
                            chequeInfo.updated_when = DateTime.Now;
                            paycheque.Update(chequeInfo);
                        }
                    }
                }

                int nTaxPaySeq = Convert.ToInt32(strPaySeq);

                if (strEventSeq == "21")
                {
                    foreach (GridDataItem item in RadGrid1.Items)
                    {
                        int nPaySeq = Convert.ToInt32(main.WebString(item["pay_seq"].Text));

                        if (item.Selected)
                        {
                            pay.UpdateTaxPaySeq(nPaySeq, nTaxPaySeq, Convert.ToInt32(Session["EmpSeq"]));
                        }
                        else
                        {
                            pay.UpdateTaxPaySeq(nPaySeq, null, Convert.ToInt32(Session["EmpSeq"]));
                        }
                    }
                }
                else if (strEventSeq == "26")
                {
                    UpdateVat(strPaySeq);
                }
            }

            cmdHistory_Click(null, null);
        }

        protected void cmdCancel1_Click(object sender, EventArgs e)
        {
            PanelEdit1.Visible = false;
            PanelView.Visible = true;
        }

        protected void cmdInsert2_Click(object sender, EventArgs e)
        {
            if (!CheckData2())
            {
                return;
            }

            Double? lstAmt = 0;
            Double? payAmt = 0;
            if (!String.IsNullOrEmpty(lblPayAmount.Text)) payAmt = Convert.ToDouble(lblPayAmount.Text);

            M_FIM_PaymentCheques info = new M_FIM_PaymentCheques();
            info.cheque_seq = main.ConvertNullInt(ddlChequeSeq.SelectedValue);
            info.cheque_name = ddlChequeSeq.Text;
            info.amount = main.ConvertNullDouble(txtChequeAmount.Text);
            info.record_status = "W";

            List<M_FIM_PaymentCheques> listInfo = (List<M_FIM_PaymentCheques>)ViewState["Cheque"];
            listInfo.Add(info);
            if (listInfo.Count > 0)
            {
                for (int i = 0; i < listInfo.Count; i++)
                {
                    lstAmt += listInfo[i].amount;
                }
                if (lstAmt > payAmt)
                {
                    main.MessageAlert(Page, "พบข้อผิดพลาด! จำนวนเงินในเช็คมากกว่าจำนวนเงินจ่าย");
                    return;
                }
            }

            ViewState["Cheque"] = listInfo;
            grdCheque.DataSource = listInfo;
            grdCheque.DataBind();

            PanelEditCheque.Visible = false;
            cmdAddNew.Visible = true;
            divControl1.Visible = true;
            lblPayChequeSeq.Text = "";
            ddlChequeSeq.SelectedIndex = 0;
        }

        protected void cmdUpdate2_Click(object sender, EventArgs e)
        {
            if (!CheckData2())
            {
                return;
            }

            List<M_FIM_PaymentCheques> listInfo = (List<M_FIM_PaymentCheques>)ViewState["Cheque"];

            M_FIM_PaymentCheques info = listInfo[Convert.ToInt32(lblIndex.Text)];
            info.cheque_seq = main.ConvertNullInt(ddlChequeSeq.SelectedValue);
            info.cheque_name = ddlChequeSeq.Text;
            info.amount = main.ConvertNullDouble(txtChequeAmount.Text);
            info.record_status = "W";

            ViewState["Cheque"] = listInfo;
            grdCheque.DataSource = listInfo;
            grdCheque.DataBind();

            PanelEditCheque.Visible = false;
            cmdAddNew.Visible = true;
            divControl1.Visible = true;
        }

        protected void cmdCancel2_Click(object sender, EventArgs e)
        {
            PanelEditCheque.Visible = false;
            cmdAddNew.Visible = true;
            divControl1.Visible = true;
        }

        protected void cmdDelete2_Click(object sender, EventArgs e)
        {
            if (lblPayChequeSeq.Text.Length > 0)
            {
                M_FIM_PaymentCheques info = new M_FIM_PaymentCheques();
                info.pay_cheque_seq = Convert.ToInt32(lblPayChequeSeq.Text);
                info.updated_by = main.ConvertNullInt(Session["EmpSeq"]);
                info.updated_when = DateTime.Now;
                paycheque.Delete(info);
            }

            List<M_FIM_PaymentCheques> listInfo = (List<M_FIM_PaymentCheques>)grdCheque.DataSource;
            listInfo.RemoveAt(Convert.ToInt32(lblIndex.Text));
            grdCheque.DataSource = listInfo;
            grdCheque.DataBind();

            PanelEditCheque.Visible = false;
            cmdAddNew.Visible = true;
            divControl1.Visible = true;
        }

        protected void ddlFilterBgmSourceSeq_SelectedIndexChanged(object o, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            lblBgmSourceName.Text = ddlFilterBgmSourceSeq.SelectedItem.Text;
            if (PanelEdit1.Visible)
            {
                LoadRadGrid1(null);
                RadGrid1.DataBind();

                if (rblEventSeq.SelectedValue == "26")
                {
                    CalCulateVat();
                }
            }
            else
            {
                LoadRadGrid2();
                RadGrid2.DataBind();
            }
            LoadDDLBankAccSeq();
            LoadDDLFromBankAccSeq();
        }

        //protected void ddlFilterWorkAreaSeq_SelectedIndexChanged(object o, RadComboBoxSelectedIndexChangedEventArgs e)
        //{
        //    LoadRadGrid1(null);
        //    RadGrid1.DataBind();
        //    LoadRadGrid2();
        //    RadGrid2.DataBind();
        //}

        //protected void ddlFilterEventSeq_SelectedIndexChanged(object o, RadComboBoxSelectedIndexChangedEventArgs e)
        //{
        //    LoadRadGrid1(null);
        //    RadGrid1.DataBind();
        //    LoadRadGrid2();
        //    RadGrid2.DataBind();
        //}

        protected void txtBgmYear_TextChanged(object sender, EventArgs e)
        {
            lblBgmYear.Text = txtBgmYear.Text;
            if (PanelEdit1.Visible)
            {
                LoadRadGrid1(null);
                RadGrid1.DataBind();
            }
            else
            {
                LoadRadGrid2();
                RadGrid2.DataBind();
            }
        }

        //==========================================================================

        protected void cmdArival_Click(object sender, EventArgs e)
        {
            cmdArival.CssClass = "LinkButtonBigBorder";
            cmdHistory.CssClass = "LinkButtonBigNoBorder";

            LoadRadGrid1(null);
            RadGrid1.DataBind();

            UpdateUI1(Mode.AddNew, false, true, rblMethodSeq.SelectedValue);
        }

        protected void cmdHistory_Click(object sender, EventArgs e)
        {
            cmdArival.CssClass = "LinkButtonBigNoBorder";
            cmdHistory.CssClass = "LinkButtonBigBorder";

            LoadRadGrid2();
            RadGrid2.DataBind();

            UpdateUI1(Mode.ViewAll, false, false, rblMethodSeq.SelectedValue);
        }

        protected void rblMethodSeq_SelectedIndexChanged(object sender, EventArgs e)
        {
            PanelCheque.Visible = rblMethodSeq.SelectedIndex == 1;
            PanelTranfer.Visible = rblMethodSeq.SelectedIndex.Equals(2) || rblMethodSeq.SelectedIndex.Equals(3);

            if (rblMethodSeq.SelectedIndex.Equals(2))
            {
                if (ViewState["_tmpConId"] != null)
                {
                    int? conid = main.ConvertNullInt(ViewState["_tmpConId"].ToString());
                    LoadDDLToContactBankAccSeq(conid);
                    ddlToBankAcc.Visible = false;
                    ddlToConBankAcc.Visible = true;
                }
                else
                {
                    int? emp_seq = null;
                    if ((ViewState["_tmpEmpSeq"] != null) && ((ViewState["_tmpConId"] == null))) emp_seq = main.ConvertNullInt(ViewState["_tmpEmpSeq"].ToString());

                    LoadDDLToBankAccSeq(emp_seq);
                    ddlToBankAcc.Visible = true;
                    ddlToConBankAcc.Visible = false;
                }
                lblFromAcc.Visible = true;
                ddlFromBankAcc.Visible = true;
            }
            else if (rblMethodSeq.SelectedIndex.Equals(3))
            {
                if (ViewState["_tmpConId"] != null)
                {
                    int? conid = main.ConvertNullInt(ViewState["_tmpConId"].ToString());
                    LoadDDLToContactBankAccSeq(conid);
                    ddlToBankAcc.Visible = false;
                    ddlToConBankAcc.Visible = true;
                }
                else
                {
                    int? emp_seq = null;
                    if ((ViewState["_tmpEmpSeq"] != null) && ((ViewState["_tmpConId"] == null))) emp_seq = main.ConvertNullInt(ViewState["_tmpEmpSeq"].ToString());

                    LoadDDLToBankAccSeq(emp_seq);
                    ddlToBankAcc.Visible = true;
                    ddlToConBankAcc.Visible = false;
                }
                lblFromAcc.Visible = false;
                ddlFromBankAcc.Visible = false;
            }
        }

        protected void ddlBankAccSeq_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            LoadDDLChequeSeq();
        }

        protected void cmdApprove_Click(object sender, EventArgs e)
        {
            PanelMessageSend.Visible = true;
            //ddlApprover.SelectedIndex = -1;
            //lblAppClassName.Text = "";
            //lblAppExecPosName.Text = "";
            //lblAppJobsiteName.Text = "";
            //lblAppPosName.Text = "";
            //lblEmpSeq.Text = "";
            LoadApprover();
            Page.SetFocus(cmdSave);
        }

        protected void LoadApprover()
        {

            cmdApprove.Visible = false;
            //cmdForword.Visible = true;
            //var pos_seq = send.GetPosSeqFromEmpSeq(Session["EmpSeq"].ToString());
            DataTable dtb = send.GetCurrentApprover(Session["EmpSeq"].ToString(), null, "FIM_PAYMENTS", 1);

            if (dtb != null)
            {
                if (dtb.Rows.Count > 0)
                {
                    lblApprovePathSeq.Text = dtb.Rows[0]["approve_path_seq"].ToString();
                    //ddlApprover.SelectedValue = dtb.Rows[0]["emp_seq"].ToString();
                    LoadEmpInfo(dtb.Rows[0]["emp_seq"].ToString());
                }
            }
        }

        protected void LoadEmpInfo(string strEmpSeq)
        {
            if (strEmpSeq.Length > 0)
            {
                var model = emplist.GetInfo(strEmpSeq);

                lblEmpSeq.Text = model.emp_seq.ToString();
                ddlApprover.Text = model.emp_name;
                lblAppPosName.Text = model.pos_name;
                lblAppClassName.Text = model.class_name;
                lblAppExecPosName.Text = model.exec_pos_name;
                lblAppJobsiteName.Text = model.job_site_name;
            }
        }

        protected void cmdRealPay_Click(object sender, EventArgs e)
        {
            PanelRealPay.Visible = true;
            txtReceiptNo.Text = "";
            txtReceiptName.Text = "";
            dpRealPayDate.SetValue(DateTime.Today);

            Page.SetFocus(cmdSave2);
        }

        protected void ddlApprover_DataBound(object sender, EventArgs e)
        {
            //set the initial footer label
            ((Literal)ddlApprover.Footer.FindControl("RadComboItemsCount")).Text = Convert.ToString(ddlApprover.Items.Count);
        }

        protected void ddlApprover_ItemsRequested(object sender, RadComboBoxItemsRequestedEventArgs e)
        {
            ddlApprover.DataSource = emplist.GetFull(null, null, null);
            ddlApprover.DataBind();
        }

        protected void ddlApprover_ItemDataBound(object sender, RadComboBoxItemEventArgs e)
        {
            e.Item.Text = ((M_HRM_PS_Employees)e.Item.DataItem).emp_name;
            e.Item.Value = ((M_HRM_PS_Employees)e.Item.DataItem).emp_seq.ToString();
        }

        protected void ddlApprover_SelectedIndexChanged(object o, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            SetEmpInfo(ddlApprover.SelectedValue);
        }

        protected void SetEmpInfo(string strEmpSeq)
        {
            if (strEmpSeq.Length > 0)
            {
                M_HRM_PS_Employees info = emplist.GetInfo(strEmpSeq);

                lblEmpSeq.Text = info.emp_seq.ToString();
                ddlApprover.Text = info.emp_name;
                lblAppPosName.Text = info.pos_name;
                lblAppClassName.Text = info.class_name;
                lblAppExecPosName.Text = info.exec_pos_name;
                lblAppJobsiteName.Text = info.working_job_site_name;
            }
        }

        protected void cmdSave_Click(object sender, EventArgs e)
        {
            if (lblEmpSeq.Text.Length == 0)
            {
                ((RadAjaxManager)Master.FindControl("RadAjaxManager1")).Alert("คำเตือน!! กรุณาเลือกผู้อนุมัติก่อนส่ง");
                //RadAjaxManager1.Alert("คำเตือน!! กรุณาเลือกผู้อนุมัติก่อนส่ง");
                return;
            }

            try
            {
                string strPaySeq = lblPaySeq.Text;
                M_MessageSend info = new M_MessageSend();
                info.send_date = DateTime.Today;
                info.ref_seq = main.ConvertNullInt(strPaySeq);
                info.ref_type = "fim_payments";
                info.ref_no = lblPayRefNo.Text;
                info.send_text = "ส่งขออนุมัติ " + txtPayName.Text;
                info.from_emp_seq = main.ConvertNullInt(Session["EmpSeq"]);
                info.from_pos_seq = send.GetPosSeqFromEmpSeq("" + Session["EmpSeq"]);
                info.to_emp_seq = main.ConvertNullInt(lblEmpSeq.Text);
                info.to_pos_seq = send.GetPosSeqFromEmpSeq(lblEmpSeq.Text);
                info.from_send_seq = null;
                info.remarks = null;
                info.message_status = "0";
                info.created_by = main.ConvertNullInt(Session["EmpSeq"]);
                info.created_when = DateTime.Now;
                send.Insert(info);

                M_FIM_Payments info2 = new M_FIM_Payments();
                info2.pay_seq = Convert.ToInt32(strPaySeq);
                info2.record_status = "P";
                info2.updated_by = main.ConvertNullInt(Session["EmpSeq"]);
                info2.updated_when = DateTime.Now;
                pay.ChangeStatus(info2);
                cmdApprove.Enabled = false;
                main.MessageAlert(Page, "บันทึกเรียบร้อยแล้ว");

                PanelMessageSend.Visible = false;
                PanelView.Visible = true;
                PanelEdit1.Visible = false;
                LoadRadGrid1(null);
                RadGrid1.DataBind();
                LoadRadGrid2();
                RadGrid2.DataBind();
            }
            catch
            {
                main.MessageAlert(Page, "เกิดข้อผิดพลาดในการบันทึกข้อมูล");
            }
        }

        protected void cmdUpdate3_Click(object sender, EventArgs e)
        {
            M_FIM_Cheques info = new M_FIM_Cheques();
            string strChequeBookSeq = lblChequeBookSeq.Text;
            string strChequeSeq = lblChequeSeq.Text;
            string strBankAccSeq = lblBankAccSeq.Text;
            string strChequeNo = lblChequeNo.Text;
            string strPaydate = dpChequePayDate.GetStringValue();
            string strChequedate = dpChequeDate.GetStringValue();
            string strReceiver = txtReceiver.Text;
            string strRemarks = txtChequeRemarks.Text;
            string strChequeStatus = rblChequeStatus.SelectedValue;
            string strUserID = Session["EmpSeq"].ToString();
            Nullable<DateTime> dtActualPayDate = txtActualPayDate.GetDateValue();
            DateTime dtNow = DateTime.Now;

            if (strChequeStatus == "3" && dtActualPayDate == null)
            {
                lblErrorActualPayDate.Visible = true;
                return;
            }

            if (strChequeStatus == "2" && main.ConvertNullDateTime(strPaydate) == null)
            {
                main.MessageAlert(Page, "กรณากรอก วันที่จ่ายเช็ค");
                lblErrorPayDate.Visible = true;
                return;
            }

            if (strChequeStatus == "3" && dtActualPayDate == null)
            {
                main.MessageAlert(Page, "กรณากรอก ขึ้นงินเมื่อวันที่");
                lblErrorActualPayDate.Visible = true;
                return;
            }

            lblErrorPayDate.Visible = false;
            lblErrorActualPayDate.Visible = false;

            info.cheque_seq = Convert.ToInt32(strChequeSeq);
            info.cheque_book_seq = main.ConvertNullInt(strChequeBookSeq);
            info.bank_acc_seq = main.ConvertNullInt(strBankAccSeq);
            info.cheque_no = main.ConvertNullInt(strChequeNo);
            info.pay_date = main.ConvertNullDateTime(strPaydate);
            info.cheque_date = main.ConvertNullDateTime(strChequedate);
            info.actual_pay_date = dtActualPayDate;
            info.receiver = strReceiver;
            info.remarks = strRemarks;
            info.cheque_status = strChequeStatus;
            info.actual_pay_date = dtActualPayDate;
            info.updated_by = main.ConvertNullInt(strUserID);
            info.updated_when = main.ConvertNullDateTime(dtNow);

            cheque.Update(info);

            //if (lblEventSeq.Text == "16" || lblEventSeq.Text == "18")
            //{
            //    mr.UpdateBorrowReturnDate(Convert.ToInt32(lblMoneyReqSeq.Text), dtActualPayDate.Value);
            //}

            LoadRadGrid2();
            PanelPayCheque.Visible = false;
        }

        protected void cmdCancel3_Click(object sender, EventArgs e)
        {
            lblChequeBookSeq.Text = "";
            lblChequeSeq.Text = "";
            lblBankAccSeq.Text = "";
            lblChequeNo.Text = "";
            dpChequePayDate.SetValue(null);
            dpChequeDate.SetValue(null);
            txtReceiver.Text = "";
            txtChequeRemarks.Text = "";
            //rblChequeStatus.SelectedValue = "";
            txtActualPayDate.SetValue(null);

            PanelPayCheque.Visible = false;
        }

        protected void rblChequeStatus_SelectedIndexChanged(object sender, EventArgs e)
        {
            liActualPayDate.Visible = rblChequeStatus.SelectedValue == "3";
        }

        protected void cmdSave2_Click(object sender, EventArgs e)
        {
            string strReceiptNo = txtReceiptNo.Text;
            string strReceiptName = txtReceiptName.Text;
            DateTime? dtRealPayDate = dpRealPayDate.GetDateValue();

            if (dtRealPayDate == null)
            {
                lblErrorRealPayDate.Visible = true;
                return;
            }
            else
            {
                lblErrorRealPayDate.Visible = false;
            }


            //if (rblEventSeq.SelectedValue == "31" || lblEventSeq.Text == "32" || lblEventSeq.Text == "34")
            //{
            //    DAL.D_FIM_MoneyRequests mrr = new DAL.D_FIM_MoneyRequests();
            //    int x = Convert.ToInt32(lblMoneyReqSeq.Text);
            //    var modelMrr= mrr.GetInfo(x);
            //    int? BidderColId = modelMrr.bidder_col_Id;
            //    mrr.UpdateBidderCol(BidderColId);
            //}

            var model = new M_FIM_Payments();
            model.pay_seq = Convert.ToInt32(lblPaySeq.Text);
            model.real_pay_date = dtRealPayDate;
            model.receipt_no = strReceiptNo;
            model.receipt_name = strReceiptName;
            model.updated_by = main.ConvertNullInt(Session["EmpSeq"].ToString());
            model.updated_when = main.ConvertNullDateTime(DateTime.Now);
            pay.UpdateReceipt(model);
            //if (lblEventSeq.Text == "16" || lblEventSeq.Text == "18")
            //{
            //    mr.UpdateBorrowReturnDate(Convert.ToInt32(lblMoneyReqSeq.Text), dtRealPayDate.Value);
            //}

            LoadRadGrid2();
            RadGrid2.DataBind();
            UpdateUI1(Mode.ViewAll, false, false, null);
        }

        protected void ddlFromBankAcc_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            //LoadDDLFromBankAccSeq();
        }

        protected void RadGrid2_ItemDataBound(object sender, GridItemEventArgs e)
        {
            if (e.Item is GridDataItem)
            {
                GridDataItem cmditem = (GridDataItem)e.Item;
                LinkButton lbtnadd = (LinkButton)cmditem.FindControl("cmdPrintPopup");
                LinkButton lbtntax = (LinkButton)cmditem.FindControl("cmdPrintPopupTax");
                lbtntax.Visible = main.WebString(cmditem["event_seq"].Text) != "26";
            }
        }

        protected void rblEventSeq_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (PanelEdit1.Visible)
            {
                if (rblEventSeq.SelectedValue == "26")
                {
                    CalCulateVat();
                    rblContactType.Visible = false;
                    tb1.Visible = false;
                    RadGrid1.Visible = false;
                    PanelPayVat.Visible = true;
                }
                else
                {
                    LoadRadGrid1(null);
                    RadGrid1.DataBind();
                    rblContactType.Visible = true;
                    tb1.Visible = true;
                    RadGrid1.Visible = true;
                    PanelPayVat.Visible = false;
                }
            }
            else
            {
                LoadRadGrid2();
                RadGrid2.DataBind();

                rblContactType.Visible = false;
                tb1.Visible = false;
            }
            lblEventName.Text = rblEventSeq.Text;
        }

        protected void RadGrid1_ItemDataBound(object sender, GridItemEventArgs e)
        {
            if (e.Item.ItemType == GridItemType.Item || e.Item.ItemType == GridItemType.AlternatingItem)
            {
                var item = (GridDataItem)e.Item;

                if (main.WebString(item["tax_pay_seq"].Text).Length > 0)
                {
                    item.Selected = true;
                }
            }
        }

        protected void ddlMonth_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            CalCulateVat();
        }

        protected void txtYear_TextChanged(object sender, EventArgs e)
        {
            CalCulateVat();
        }

        private void CalCulateVat()
        {
            if (ddlMonth.SelectedValue.Length > 0 && txtYear.Text.Length == 4 && ddlFilterBgmSourceSeq.SelectedValue.Length > 0)
            {
                int nMonth = Convert.ToInt32(ddlMonth.SelectedValue);
                int nYear = Convert.ToInt32(txtYear.Text);
                int nBgmSourceSeq = main.ConvertNullInt(ddlFilterBgmSourceSeq.SelectedValue) ?? 0;
                int? nPaySeq = main.ConvertNullInt(lblPaySeq.Text);
                DataTable dtbBuy = pay.GetVatBuy(nMonth, nYear, null, nPaySeq);
                DataTable dtbSale = pay.GetVatSale(nMonth, nYear, null, nPaySeq);
                double dBuyAmount = dtbBuy.Rows.Count > 0 ? (main.ConvertNullDouble(dtbBuy.Rows[0]["amount"]) ?? 0) : 0;
                double dSaleAmount = dtbSale.Rows.Count > 0 ? (main.ConvertNullDouble(dtbSale.Rows[0]["amount"]) ?? 0) : 0;
                double dNonSaleAmount = dtbSale.Rows.Count > 0 ? (main.ConvertNullDouble(dtbSale.Rows[0]["non_vat_sale_amount"]) ?? 0) : 0;
                double dPrevVatAmount = pay.GetPrevVatBuySale(nMonth, nYear);
                double dVatBuyAmount = dtbBuy.Rows.Count > 0 ? (main.ConvertNullDouble(dtbBuy.Rows[0]["amount_vat"]) ?? 0) : 0;
                double dCalVatBuyAmount = dtbBuy.Rows.Count > 0 ? (main.ConvertNullDouble(dtbBuy.Rows[0]["amount_vat"]) ?? 0) : 0;
                double dDiffVatBuyAmount = dVatBuyAmount - dCalVatBuyAmount;
                double dVatSaleAmount = dSaleAmount * 7 / 107;//(dSaleAmount - (dtbSale.Rows.Count > 0 ? (main.ConvertNullDouble(dtbSale.Rows[0]["amount_vat"]) ?? 0) : 0)) * 7 / 100;
                double dCalVatSaleAmount = dtbSale.Rows.Count > 0 ? (main.ConvertNullDouble(dtbSale.Rows[0]["amount_vat"]) ?? 0) : 0;
                double dDiffVatSaleAmount = dVatSaleAmount - dCalVatSaleAmount;

                lblPrevVatAmount.Text = dPrevVatAmount.ToString("#,##0.00");
                lblVatBuyAmount.Text = dVatBuyAmount.ToString("#,##0.00");
                lblVatSaleAmount.Text = dVatSaleAmount.ToString("#,##0.00");
                lblVatAmount.Text = (dVatSaleAmount - dVatBuyAmount).ToString("#,##0.00");
                lblPayAmount.Text = dVatSaleAmount - dVatBuyAmount - dPrevVatAmount > 0 ? (dVatSaleAmount - dVatBuyAmount - dPrevVatAmount).ToString("#,##0.00") : "0.00";
                lblTotal.Text = (dVatSaleAmount - dVatBuyAmount - dPrevVatAmount).ToString("#,##0.00");

                lblBuyAmount.Text = dBuyAmount.ToString("#,##0.00");
                lblSaleAmount.Text = dSaleAmount.ToString("#,##0.00");
                lblNonVatSaleAmount.Text = dNonSaleAmount.ToString("#,##0.00");
                lblNext.Text = dVatSaleAmount - dVatBuyAmount - dPrevVatAmount > 0 ? "0.00" : (dVatBuyAmount + dPrevVatAmount - dVatSaleAmount).ToString("#,##0.00");

                lblCalVatBuyAmount.Text = dCalVatBuyAmount.ToString("#,##0.00");
                lblCalVatSaleAmount.Text = dCalVatSaleAmount.ToString("#,##0.00");
                lblDiffVatBuyAmount.Text = dDiffVatBuyAmount.ToString("#,##0.00");
                lblDiffVatSaleAmount.Text = dDiffVatSaleAmount.ToString("#,##0.00");

                divPayment.Visible = (dVatSaleAmount - dVatBuyAmount - dPrevVatAmount) > 0;
            }
        }

        protected void rblContactType_SelectedIndexChanged(object sender, EventArgs e)
        {
            LoadRadGrid1(main.ConvertNullInt(lblPaySeq.Text), 21);
            RadGrid1.DataBind();
        }

        protected void ddlMonth2_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            LoadRadGrid1(main.ConvertNullInt(lblPaySeq.Text), 21);
            RadGrid1.DataBind();
        }

        protected void txtYear2_TextChanged(object sender, EventArgs e)
        {
            LoadRadGrid1(main.ConvertNullInt(lblPaySeq.Text), 21);
            RadGrid1.DataBind();
        }
    }
}
